package com.example.ai.view

import androidx.annotation.OptIn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.SecureFlagPolicy
import androidx.media3.common.C
import androidx.media3.common.MediaMetadata
import androidx.media3.common.MimeTypes
import androidx.media3.common.Player
import androidx.media3.common.util.UnstableApi
import com.example.ai.model.viewmodel.MessageViewModel
import io.sanghun.compose.video.RepeatMode
import io.sanghun.compose.video.VideoPlayer
import io.sanghun.compose.video.controller.VideoPlayerControllerConfig
import io.sanghun.compose.video.uri.VideoPlayerMediaItem

/**
 * Created by lijinxi on 2024/3/9.
 * @Description:
 */
@OptIn(UnstableApi::class)
@Composable
fun VideoPlayContent(
    playList: SnapshotStateList<Pair<Int, String>>,
    viewModel: MessageViewModel
) {
    VideoPlayer(
        mediaItems = mutableListOf<VideoPlayerMediaItem>().apply {
            playList.forEach {
                add(
                    VideoPlayerMediaItem.NetworkMediaItem(
                        url = it.second,
                        mediaMetadata = MediaMetadata.Builder().build(),
                        mimeType = MimeTypes.APPLICATION_MP4,
                    )
                )
                viewModel.preConsume(it.first)
            }
        },
        handleLifecycle = true,
        repeatMode = RepeatMode.NONE,
        autoPlay = true,
        usePlayerController = false,
        enablePipWhenBackPressed = false,
        enablePip = false,
        controllerConfig = VideoPlayerControllerConfig.Default.copy(),
        onCurrentTimeChanged = {
        },
        fullScreenSecurePolicy = SecureFlagPolicy.SecureOn,
        playerInstance = {
            this.videoScalingMode = C.VIDEO_SCALING_MODE_SCALE_TO_FIT
            addListener(object : Player.Listener {
                @OptIn(UnstableApi::class)
                override fun onPlaybackStateChanged(playbackState: Int) {
                    super.onPlaybackStateChanged(playbackState)
                    if (playbackState == Player.STATE_ENDED) {
                        viewModel.finalConsume()
                    }
                }
            })
        },
        modifier = Modifier.clip(RoundedCornerShape(16.dp))
    )
}

